//
//  CutoutCollageViewController.swift
//  SwiftPhtotEdit
//
//  Created by aw031 on 13/10/2025.
//

import UIKit
import SnapKit
class CutoutCollageViewController: UIViewController {
    
    // MARK: - IBOutlets
    lazy var backView: UIView = {
        let view = UIView()
        view.layer.masksToBounds = true
        return view
    }()
    
    lazy var imageBGView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.cyan
        view.layer.masksToBounds = true
        return view
    }()
        
    lazy var imageView: UIImageView = {
        let imgView = UIImageView(image: KImage("123456"))
        imgView.contentMode = .scaleAspectFit
        imgView.backgroundColor = .red
        return imgView
    }()
    
    
    lazy var autoCutBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("auto", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        
        btn.setCustomImage(UIImage.init(systemName: "star"))
        btn.setCustomImage(UIImage.init(systemName: "star.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        
        btn.addTarget(self, action: #selector(autocutBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var lassoCutBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("lassoCut", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        
        btn.setCustomImage(UIImage.init(systemName: "star.hexagon"))
        btn.setCustomImage(UIImage.init(systemName: "star.hexagon.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(lassoCutBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var eraseBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("erase", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        
        btn.setCustomImage(UIImage.init(systemName: "pencil.tip.crop.circle"))
        btn.setCustomImage(UIImage.init(systemName: "pencil.tip.crop.circle.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(eraseBtnClick), for: .touchUpInside)
        return btn
    }()
    
    
    lazy var photoBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("photo", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.backgroundColor = .cyan
        btn.setCustomImage(UIImage.init(systemName: "photo.stack"))
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(photoClickUpInside), for: .touchUpInside)
        return btn
    }()

    
    
    lazy var eraserIconView: UIView = {
        let view = UIImageView()
        view.backgroundColor = UIColor.red.withAlphaComponent(0.2)
//        view.layer.cornerRadius = self.tagIconImageSize.width/2.0;
        view.layer.borderColor  = UIColor.white.cgColor
//        view.layer.borderWidth = 2
        view.layer.masksToBounds = true
        return view
    }()
    
    
    
    // MARK: - Properties
    //擦除和刷子的path
    var erasePath: UIBezierPath?
    //刷子
    var brushStack: [UIBezierPath] = []
    //擦除
    var restoreStack: [UIBezierPath] = []
    //用于原始的图片
    var originalImage: UIImage?
    //修改的图片
    var sourceImage: UIImage?
    
    var lastTouchPoint: CGPoint = .zero
   //获取服务器抠图的图片
    var cutImage: UIImage?
    //是不是刷子的操作
    var isBrush: Bool = false
    //是否可以编辑
    var isAllowEdit: Bool = false
    
    var lastScale : CGFloat = 1
    
    lazy var pinch: UIPinchGestureRecognizer = {
       let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        return pinchGesture
    }()
    
//    var taskCount: Int = 0
    //是否是放大缩小
    var isPinching: Bool = false
    //用户设置的大小默认 50
    var lineWidth : CGFloat  = 50
    //画笔的粗细
    var brushWidth : CGFloat = 50
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 更好的时机
        navigationController?.navigationBar.isHidden = true
        navigationController?.setNavigationBarHidden(true, animated: false)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        // Do any additional setup after loading the view.
        
//        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        let btn = UIButton(type: .custom)
        btn.setTitle("<", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.addTarget(self, action: #selector(clickUpdataAction), for: .touchUpInside)
        self.view.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.top.equalTo(KStatusBarHeight)
            make.leading.equalTo(16)
            make.width.height.equalTo(44)
        }
        self.setUpDataUI()
        // 开启用户交互
        self.sourceImage = self.imageView.image
        self.originalImage = self.sourceImage
        
        // 添加捏合手势
        pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        self.imageView.addGestureRecognizer(self.pinch)
        
        // 添加拖拽手势（仅支持双指平移）
        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        pan.minimumNumberOfTouches = 2
        pan.maximumNumberOfTouches = 2
        self.imageView.addGestureRecognizer(pan)
        
        
        self.view.layoutIfNeeded()
        self.updataLineWidth(lineWidth: self.lineWidth)
    }
    
    @objc func clickUpdataAction(_ sender : UIButton) {
        navigationController?.popViewController(animated: true)
    }
    override func viewDidAppear(_ animated: Bool) {
        self.updataLineWidth(lineWidth: self.lineWidth)
    }
    
    func setUpDataUI() {
        // MARK: - IBOutlets
        view.addSubview(backView)
        backView.addSubview(imageBGView)
        imageBGView.addSubview(imageView)
        
        backView.addSubview(autoCutBtn)
        backView.addSubview(lassoCutBtn)
        backView.addSubview(eraseBtn)
        backView.addSubview(photoBtn)
        
        backView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(KStatusAndNavigationHeight)
            make.leading.bottom.trailing.equalToSuperview()
        }
        
        imageBGView.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(300)
        }
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        autoCutBtn.snp.makeConstraints { make in
            make.top.equalTo(imageBGView.snp.bottom).offset(30)
            make.leading.equalTo(16)
            make.height.equalTo(60)
        }
        
        
        
        lassoCutBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(autoCutBtn.snp.trailing).offset(16)
        }
        
        
        eraseBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(lassoCutBtn.snp.trailing).offset(16)
        }
        
        
        photoBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(eraseBtn.snp.trailing).offset(16)
            make.trailing.equalTo(-16)
        }
        
        
    }
    
    func setImage(_ image: UIImage) {
        self.sourceImage = image
        self.imageView.image = image
        
        self.autocutBtnClick(self.autoCutBtn)
    }
    
    // MARK: - Button Actions
    @objc func autocutBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        lassoCutBtn.isSelected = false
        eraseBtn.isSelected = false
        isAllowEdit = false
        eraserIconView.isHidden = true
     
        if sender.isSelected {
            if let cutImage = self.cutImage {
                self.imageView.image = cutImage
                self.originalImage = cutImage
                
                self.resetTouchData()
            } else {
                self.loadResultData(self.sourceImage)
            }
        } else {
            self.imageView.image = self.sourceImage
            self.originalImage = self.sourceImage
            
            self.resetTouchData()
        }
    }
    
    //刷子
    @objc func lassoCutBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        eraseBtn.isSelected = false
        isAllowEdit = sender.isSelected
        
        //        if let eraserIconView = self.eraserIconView {
//        eraserIconView.isHidden = !sender.isSelected
        //        }
        
        //        lassoCutImgView.image = UIImage(named: sender.isSelected ? "make_lassocut_sel" : "make_lassocut_nor")
        //        eraseImgView.image = UIImage(named: "make_erase_nor")
        //        lassoCutLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")
        //        eraseLabel.textColor = UIColor(hexString: "#141415")
        
        if !sender.isSelected { return }
        
        self.isBrush = true
        self.originalImage = self.imageView.image
        
//        self.eraserIconView.center = self.imageView.center
//        self.imageView.addSubview(eraserIconView)
    }
    
    //擦除
    @objc func eraseBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        lassoCutBtn.isSelected = false
        isAllowEdit = sender.isSelected
            
        if !sender.isSelected { return }
        
        self.isBrush = false
        self.originalImage = self.imageView.image

    }
    
    @IBAction func backBtnClick(_ sender: UIButton) {
        self.backView.removeFromSuperview()
    }
    
    @IBAction func saveBtnClick(_ sender: UIButton) {
        // 注意：这里需要替换为实际的 PurchaseManager 和 CommonClass 实现
        /*
         if !PurchaseManager.shared.isMember && CommonClass.showCutout() {
         let vc = PremiumEditionController()
         if let currentVC = CommonClass.currentViewController() {
         currentVC.navigationController?.pushViewController(vc, animated: true)
         }
         } else {
         if self.imageView.image != nil {
         CommonClass.updateCutout(true)
         }
         
         self.saveBtnClick?(self.imageView.image)
         }
         */
        
        // 临时实现 - 直接保存
//        self.saveBtnClick?(self.imageView.image)
    }
    
    // MARK: - Touch Handling
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isAllowEdit || isPinching { return }
        guard let touch = touches.first else { return }
        
        
        let touchInViewPoint = touch.location(in: self.imageView)
        self.eraserIconView.center = self.imageView.center
        self.imageView.addSubview(eraserIconView)
       
        eraserIconView.isHidden = false
        eraserIconView.center = touchInViewPoint
        
        if self.erasePath == nil {
            self.erasePath = UIBezierPath()
            //设置线的大小
            self.erasePath?.lineWidth = self.brushWidth
            self.erasePath?.lineCapStyle = .round
        }
        
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isAllowEdit || isPinching { return }
        
        guard let touch = touches.first else { return }
        guard let img = self.sourceImage else { return }

        let touchInViewPoint = touch.location(in: self.imageView)
        eraserIconView.center = touchInViewPoint
        
        guard let _ = self.originalImage else { return }
        
  
        let currentPoint = getTouchPoint(img: img, touchInViewPoint: touchInViewPoint)

        if self.lastTouchPoint == .zero {
            self.erasePath?.move(to: currentPoint)
        } else {
            let midPoint = CGPoint(
                x: (self.lastTouchPoint.x + currentPoint.x) / 2.0,
                y: (self.lastTouchPoint.y + currentPoint.y) / 2.0
            )
            self.erasePath?.addQuadCurve(to: midPoint, controlPoint: self.lastTouchPoint)
        }
        
        self.lastTouchPoint = currentPoint
        
        self.renderMask()
        print("touchesMoved ====  \(touchInViewPoint)")
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isAllowEdit || isPinching { return }
        
        if let erasePath = self.erasePath, !erasePath.isEmpty {
            if self.isBrush {
                if self.restoreStack.isEmpty {
                    self.restoreStack = []
                }
                self.restoreStack.append(erasePath.copy() as! UIBezierPath)
                // 恢复操作，清除擦除轨迹
                self.brushStack.removeAll()
            } else {
                if self.brushStack.isEmpty {
                    self.brushStack = []
                }
                self.brushStack.append(erasePath.copy() as! UIBezierPath)
                // 擦除操作，清除恢复轨迹
                self.restoreStack.removeAll()
            }
            
            
        }
 
        self.eraserIconView.isHidden = true
        self.erasePath = nil
        self.lastTouchPoint = .zero
        print("touchesEnded ==== ")
    }
    
    
    // 获取图片中画笔的粗细比例方法：
    private func convertToImageLineWidthScale() -> CGFloat {
        guard let img = self.sourceImage else { return 1 }
        
        let imageSize = img.size
        let imageViewSize = self.imageBGView.bounds.size
        
//        print("sourceImage 图片的大小 \(imageSize) ----- originalImage 图片的大小 \(originalImage!.size) ----imageViewSize  \(imageViewSize)")
        // 计算图像在UIImageView中的实际显示尺寸
        let imageScale = min(imageViewSize.width / imageSize.width, imageViewSize.height / imageSize.height)
        let fittedImageSize = CGSize(
            width: imageSize.width * imageScale,
            height: imageSize.height * imageScale
        )
        
        // 计算从视图坐标到图像坐标的转换比例
        let scaleToImage = imageSize.width / fittedImageSize.width
        
        return scaleToImage / (self.imageView.transform.a)
    }
    
    //获取对应手指所在位置
    func getTouchPoint(img : UIImage , touchInViewPoint : CGPoint) -> CGPoint {
        let imageSize = img.size
        let imageViewSize = self.imageView.bounds.size
        let scale = min(imageViewSize.width / imageSize.width, imageViewSize.height / imageSize.height)
        let fittedImageSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
        let x = (imageViewSize.width - fittedImageSize.width) / 2.0
        let y = (imageViewSize.height - fittedImageSize.height) / 2.0
        
        let currentPoint = CGPoint(
            x: (touchInViewPoint.x - x) * (imageSize.width / fittedImageSize.width),
            y: (touchInViewPoint.y - y) * (imageSize.height / fittedImageSize.height)
        )
        return currentPoint
    }
    // MARK: - Mask Rendering
    func renderMask() {
        guard let sourceImage = self.sourceImage else { return }
        
        UIGraphicsBeginImageContextWithOptions(sourceImage.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        
        self.originalImage?.draw(at: .zero)
        
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.saveGState()
        
        ctx.setLineCap(.round)
        ctx.setLineWidth(self.brushWidth)
        
        if self.isBrush {
            for path in self.restoreStack {
                ctx.saveGState()
                ctx.addPath(path.cgPath)
                ctx.replacePathWithStrokedPath()
                ctx.clip()
                sourceImage.draw(at: .zero)
                ctx.restoreGState()
            }
            if let erasePath = self.erasePath {
                ctx.saveGState()
                ctx.addPath(erasePath.cgPath)
                ctx.replacePathWithStrokedPath()
                ctx.clip()
                sourceImage.draw(at: .zero)
                ctx.restoreGState()
            }
        } else {
            ctx.setBlendMode(.clear)
            ctx.setStrokeColor(UIColor.clear.cgColor)
            let paths = self.brushStack
            for path in paths {
                ctx.addPath(path.cgPath)
                ctx.strokePath()
            }
            if let erasePath = self.erasePath {
                ctx.addPath(erasePath.cgPath)
                ctx.strokePath()
            }
        }
        
        ctx.restoreGState()
        
        if let result = UIGraphicsGetImageFromCurrentImageContext() {
            self.imageView.image = result
            self.originalImage = result
        }
    }
    
    func resetTouchData() {
        self.brushStack.removeAll()
        self.restoreStack.removeAll()
        self.erasePath = nil
        self.lastTouchPoint = .zero
    }
    
    // MARK: - Album
    @objc func photoClickUpInside() {
        // 需要实现权限检查和相册访问
        /*
         PermissionManager.checkPhotoLibraryPermission()
         let imagePickerController = UIImagePickerController()
         imagePickerController.delegate = self
         imagePickerController.allowsEditing = false
         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
         imagePickerController.sourceType = .photoLibrary
         self.viewController?.present(imagePickerController, animated: true)
         }
         */
        PhotoTools.shared.showPhotoAndCameraPicker(in: self, isPhoto: true, resultHandler:{ [weak self] img in
            //            self??.pushBackgroundEditVC(image: img,isPhoto: true) { image in
            //                self?.changeBackground(selectStyle: 1, colors: [], backImage: image)
            //            }
            //            if let image = info[.originalImage] as? UIImage {
            self?.sourceImage = img
            self?.imageView.image = img
            self?.autocutBtnClick(self!.autoCutBtn)
            //            }
        })
    }
    
    // MARK: - Network Requests
    func loadResultData(_ image: UIImage?) {
        guard let image = image else {
            // PSProgressHUD.showToast("The image cannot be empty", view: self)
            return
        }
        
        // PSProgressHUD.show(in: self)
        
        // 需要实现网络请求逻辑
        /*
         let request = UploadImageRequest()
         request.image = image
         
         request.startWithCompletionBlock(success: { [weak self] request in
         guard let self = self else { return }
         if let responseDict = request.responseObject as? [String: Any],
         let code = responseDict["code"] as? NSNumber, code == 0,
         let data = responseDict["data"] as? [String: Any],
         let filePath = data["filePath"] as? String {
         self.createTask(filePath)
         } else {
         // PSProgressHUD.hide(in: self)
         // PSProgressHUD.showToast("Please try again later", view: self)
         }
         }, failure: { [weak self] request, message in
         guard let self = self else { return }
         // PSProgressHUD.hide(in: self)
         // PSProgressHUD.showToast("Please try again later", view: self)
         })
         */
    }
    
    func createTask(_ filePath: String) {
        // 实现创建任务的网络请求
    }
    
    func taskStatus(_ taskId: String) {
        // 实现任务状态查询的网络请求
    }
    
    
    func updataLineWidth(lineWidth : CGFloat) {
        
        let scale  = convertToImageLineWidthScale()

        
        let iconWidth = self.lineWidth / self.imageView.transform.a
        let tempLineWidth  = self.lineWidth * scale
        
        self.eraserIconView.frame.size = CGSizeMake(iconWidth,iconWidth)
        self.eraserIconView.layer.cornerRadius = iconWidth/2.0
        self.eraserIconView.layer.borderWidth = 2 / self.imageView.transform.a
        
        self.brushWidth = tempLineWidth
        
    }
    
////     MARK: --  双指放大移动
//    @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
//        switch pinch.state {
//        case .began, .changed:
//            self.isPinching = true
//        case .ended, .cancelled:
//            self.isPinching = false
//            
//            
//        default:
//            break
//        }
//        
//        print("捏合 , \(pinch.scale)")
//        // 在当前 transform 上叠加缩放
//        if let view = pinch.view {
//            view.transform = view.transform.scaledBy(x: pinch.scale, y: pinch.scale)
//        }
//        pinch.scale = 1.0 // 重置 scale，避免叠加
//        
//        if pinch.state == .ended || pinch.state == .cancelled {
//            updataLineWidth(lineWidth: self.lineWidth)
//        }
////        self.resetTouchData()
//        
//    }
//
//    @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
//        guard let view = pinch.view else { return }
//        
//        switch pinch.state {
//        case .began:
//            
//            self.isPinching = true
//            // 保存初始transform，用于后续计算
//            self.lastScale = 1.0
//            
//            let touchInViewPoint = pinch.location(ofTouch: 0, in: self.imageView)
//            eraserIconView.isHidden = true
//            eraserIconView.center = touchInViewPoint
//            
//        case .changed:
//            
//            self.isPinching = true
//            
//            // 基于原始大小的相对缩放
//            let currentScale = pinch.scale
//            let scaleChange = currentScale / self.lastScale
//            
//            // 在当前transform基础上应用缩放变化
//            view.transform = view.transform.scaledBy(x: scaleChange, y: scaleChange)
//            self.lastScale = currentScale
//            
//        case .ended, .cancelled, .failed:
//            self.isPinching = false
//            self.lastScale = 1.0
//            
//            // 可选：限制最小和最大缩放
//            let minScale: CGFloat = 1
//            let maxScale: CGFloat = CGFLOAT_MAX
//            
//            let currentScale = view.transform.a // 获取x轴缩放值
//            
//            if currentScale < minScale {
//                UIView.animate(withDuration: 0.2) {
//                    view.transform = CGAffineTransform(scaleX: minScale, y: minScale)
//                }
//            } else if currentScale > maxScale {
//                UIView.animate(withDuration: 0.2) {
//                    view.transform = CGAffineTransform(scaleX: maxScale, y: maxScale)
//                }
//            }
//            
//            
//            updataLineWidth(lineWidth: self.lineWidth)
//          
//            print("放大缩小")
//            
//        default:
//            break
//        }
//    }
//     //MARK: --  双指移动
//    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
//        guard let piece = pan.view else { return }
//        let translation = pan.translation(in: piece.superview)
//        
//        switch pan.state {
//        case .began, .changed:
//            piece.center = CGPoint(x: piece.center.x + translation.x, y: piece.center.y + translation.y)
//            pan.setTranslation(.zero, in: piece.superview)
//            self.isPinching = true // 复用 isPinching 标志禁止绘制
//        case .ended, .cancelled:
//            self.isPinching = false
//        default:
//            break
//        }
////        self.resetTouchData()
//    }
    
//    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
//        guard let piece = pan.view, let superview = piece.superview else { return }
//        let translation = pan.translation(in: superview)
//
//        switch pan.state {
//        case .began, .changed:
//            piece.center = CGPoint(x: piece.center.x + translation.x,
//                                   y: piece.center.y + translation.y)
//            pan.setTranslation(.zero, in: superview)
//            self.isPinching = true
//
//        case .ended, .cancelled:
//            self.isPinching = false
//
//            // 把 view 的 bounds 转换到 superview 坐标系，
//            // 这样会把 transform（缩放/旋转）算进来，得到真实显示矩形。
//            let transformedFrame = piece.convert(piece.bounds, to: superview)
//            let superBounds = superview.bounds
//
//            // 计算需要的偏移（以 superview 坐标系的量）
//            var offsetX: CGFloat = 0
//            var offsetY: CGFloat = 0
//
//            // 左边超出（左边小于 superview 左）
//            if transformedFrame.minX < superBounds.minX {
//                offsetX = superBounds.minX - transformedFrame.minX
//            }
//            // 右边超出（右边大于 superview 右）
//            else if transformedFrame.maxX > superBounds.maxX {
//                offsetX = superBounds.maxX - transformedFrame.maxX
//            }
//
//            // 上边超出（上边小于 superview 上）
//            if transformedFrame.minY < superBounds.minY {
//                offsetY = superBounds.minY - transformedFrame.minY
//            }
//            // 下边超出（下边大于 superview 下）
//            else if transformedFrame.maxY > superBounds.maxY {
//                offsetY = superBounds.maxY - transformedFrame.maxY
//            }
//
//            // 如果需要修正，则把偏移从 superview 坐标系转换为 piece.center 的偏移量并动画回弹
//            if offsetX != 0 || offsetY != 0 {
//                // 注意：transformedFrame 的偏移就是 superview 坐标系下的偏移，
//                // 直接加到 piece.center（也是 superview 坐标系）即可
//                let newCenter = CGPoint(x: piece.center.x + offsetX,
//                                        y: piece.center.y + offsetY)
//
//                UIView.animate(withDuration: 0.35,
//                               delay: 0,
//                               usingSpringWithDamping: 0.8,
//                               initialSpringVelocity: 1.0,
//                               options: [.curveEaseOut]) {
//                    piece.center = newCenter
//                }
//            }
//
//        default:
//            break
//        }
//    }

//    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
//        guard let piece = pan.view, let superview = piece.superview else { return }
//        let translation = pan.translation(in: superview)
//
//        switch pan.state {
//        case .began, .changed:
//            piece.center = CGPoint(x: piece.center.x + translation.x,
//                                   y: piece.center.y + translation.y)
//            pan.setTranslation(.zero, in: superview)
//            self.isPinching = true
//
//        case .ended, .cancelled:
//            self.isPinching = false
//
//            let velocity = pan.velocity(in: superview)
//            let transformedFrame = piece.convert(piece.bounds, to: superview)
//            let superBounds = superview.bounds
//
//            var finalFrame = transformedFrame
//
//            let velocityThreshold: CGFloat = 5.0
//
//            // 检查水平边界
//            if abs(velocity.x) > velocityThreshold {
//                if velocity.x > 0 {
//                    // 向右拖动 -> 检查左边界是否没有超出父视图左边界（即还在内部）
//                    if transformedFrame.minX > superBounds.minX {
//                        finalFrame.origin.x = superBounds.minX
//                    }
//                } else {
//                    // 向左拖动 -> 检查右边界是否没有超出父视图右边界（即还在内部）
//                    if transformedFrame.maxX < superBounds.maxX {
//                        finalFrame.origin.x = superBounds.maxX - transformedFrame.width
//                    }
//                }
//            }
//
//            // 检查垂直边界
//            if abs(velocity.y) > velocityThreshold {
//                if velocity.y > 0 {
//                    // 向下拖动 -> 检查上边界是否没有超出父视图上边界（即还在内部）
//                    if transformedFrame.minY > superBounds.minY {
//                        finalFrame.origin.y = superBounds.minY
//                    }
//                } else {
//                    // 向上拖动 -> 检查下边界是否没有超出父视图下边界（即还在内部）
//                    if transformedFrame.maxY < superBounds.maxY {
//                        finalFrame.origin.y = superBounds.maxY - transformedFrame.height
//                    }
//                }
//            }
//
//            // 如果速度很小，检查所有边界
//            if abs(velocity.x) <= velocityThreshold && abs(velocity.y) <= velocityThreshold {
//                // 对于速度很小的情况，可以保持原样或者吸附到最近的边界
//                // 这里保持原样，不进行吸附
//            }
//
//            // 如果frame有变化，执行动画
//            if !finalFrame.equalTo(transformedFrame) {
//                let newCenter = CGPoint(
//                    x: finalFrame.midX,
//                    y: finalFrame.midY
//                )
//                UIView.animate(withDuration: 0.35,
//                               delay: 0,
//                               usingSpringWithDamping: 0.8,
//                               initialSpringVelocity: 1.0,
//                               options: [.curveEaseOut]) {
//                    piece.center = newCenter
//                }
//            }
//
//        default:
//            break
//        }
//        print("平移")
//
//    }

//    @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
//        guard let view = pinch.view else { return }
//        
//        switch pinch.state {
//        case .began:
//            self.isPinching = true
//            self.lastScale = 1.0
//            let touchInViewPoint = pinch.location(ofTouch: 0, in: self.imageView)
//            eraserIconView.isHidden = true
//            eraserIconView.center = touchInViewPoint
//            
//        case .ended, .cancelled, .failed ,.changed:
//            self.isPinching = false
//            self.lastScale = 1.0
//            
//            // 限制最小和最大缩放
//            let minScale: CGFloat = 1
//            let maxScale: CGFloat = CGFLOAT_MAX
//            
//            let currentScale = view.transform.a
//            
//            if currentScale < minScale {
//                UIView.animate(withDuration: 0.2) {
//                    view.transform = CGAffineTransform(scaleX: minScale, y: minScale)
//                    self.checkAndAdjustBounds(for: view)
//                }
//            } else if currentScale > maxScale {
//                UIView.animate(withDuration: 0.2) {
//                    view.transform = CGAffineTransform(scaleX: maxScale, y: maxScale)
//                    self.checkAndAdjustBounds(for: view)
//                }
//            } else {
//                // 即使没有缩放限制，也要检查边界
//                self.checkAndAdjustBounds(for: view, animated: true)
//            }
//            
//            updataLineWidth(lineWidth: self.lineWidth)
//            print("放大缩小")
//            
//        default:
//            break
//        }
//    }
//
//    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
//        guard let piece = pan.view, let superview = piece.superview else { return }
//        let translation = pan.translation(in: superview)
//
//        switch pan.state {
//        case .began :
//            piece.center = CGPoint(x: piece.center.x + translation.x,
//                                   y: piece.center.y + translation.y)
//            pan.setTranslation(.zero, in: superview)
//            self.isPinching = true
//            
//            // 实时检查边界
//            checkAndAdjustBounds(for: piece, duringPan: true)
//
//        case .ended, .cancelled, .changed:
//            self.isPinching = false
//            // 最终边界检查
//            checkAndAdjustBounds(for: piece, animated: true)
//            print("平移")
//
//        default:
//            break
//        }
//    }
//
//    // 统一的边界检查方法
//    private func checkAndAdjustBounds(for view: UIView, duringPan: Bool = false, animated: Bool = false) {
//        guard let superview = view.superview else { return }
//        
//        let transformedFrame = view.convert(view.bounds, to: superview)
//        let superBounds = superview.bounds
//        
//        var finalFrame = transformedFrame
//        var needsAdjustment = false
//        
//        // 检查左边界
//        if transformedFrame.minX > superBounds.minX {
//            finalFrame.origin.x = superBounds.minX
//            needsAdjustment = true
//        }
//        
//        // 检查右边界
//        if transformedFrame.maxX < superBounds.maxX {
//            finalFrame.origin.x = superBounds.maxX - transformedFrame.width
//            needsAdjustment = true
//        }
//        
//        // 检查上边界
//        if transformedFrame.minY > superBounds.minY {
//            finalFrame.origin.y = superBounds.minY
//            needsAdjustment = true
//        }
//        
//        // 检查下边界
//        if transformedFrame.maxY < superBounds.maxY {
//            finalFrame.origin.y = superBounds.maxY - transformedFrame.height
//            needsAdjustment = true
//        }
//        
//        // 如果视图完全超出边界，将其拉回
//        if transformedFrame.maxX < superBounds.minX || transformedFrame.minX > superBounds.maxX ||
//           transformedFrame.maxY < superBounds.minY || transformedFrame.minY > superBounds.maxY {
//            
//            // 居中显示
//            finalFrame.origin.x = (superBounds.width - transformedFrame.width) / 2
//            finalFrame.origin.y = (superBounds.height - transformedFrame.height) / 2
//            needsAdjustment = true
//        }
//        
//        // 如果需要调整且不是在平移过程中（平移过程中已经实时处理）
//        if needsAdjustment && !duringPan {
//            let newCenter = CGPoint(
//                x: finalFrame.midX,
//                y: finalFrame.midY
//            )
//            
//            if animated {
//                UIView.animate(withDuration: 0.35,
//                               delay: 0,
//                               usingSpringWithDamping: 0.8,
//                               initialSpringVelocity: 1.0,
//                               options: [.curveEaseOut]) {
//                    view.center = newCenter
//                }
//            } else {
//                view.center = newCenter
//            }
//        }
//    }
//
//    // 同时处理缩放和平移的手势识别器代理方法
//    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
//        // 允许缩放和平移手势同时进行
//        return (gestureRecognizer is UIPinchGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer) ||
//               (gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPinchGestureRecognizer)
//    }
//
    
    @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
        guard let view = pinch.view else { return }
        
        switch pinch.state {
        case .began:
            self.isPinching = true
            self.lastScale = 1.0
            let touchInViewPoint = pinch.location(ofTouch: 0, in: self.imageView)
            eraserIconView.isHidden = true
            eraserIconView.center = touchInViewPoint
            
        case .changed:
            self.isPinching = true
            
            let currentScale = pinch.scale
            let scaleChange = currentScale / self.lastScale
            
            // 应用缩放变化
            view.transform = view.transform.scaledBy(x: scaleChange, y: scaleChange)
            self.lastScale = currentScale
            
        case .ended, .cancelled, .failed:
            self.isPinching = false
            self.lastScale = 1.0
            
            // 限制最小和最大缩放
            let minScale: CGFloat = 1
            let maxScale: CGFloat = CGFLOAT_MAX
            
            let currentScale = view.transform.a
            
            if currentScale < minScale {
                UIView.animate(withDuration: 0.2) {
                    view.transform = CGAffineTransform(scaleX: minScale, y: minScale)
                }
            } else if currentScale > maxScale {
                UIView.animate(withDuration: 0.2) {
                    view.transform = CGAffineTransform(scaleX: maxScale, y: maxScale)
                }
            }
            
            // 缩放结束后检查边界
            checkAndAdjustBounds(for: view, animated: true)
            
            updataLineWidth(lineWidth: self.lineWidth)
            print("放大缩小")
            
        default:
            break
        }
    }

    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
        guard let piece = pan.view, let superview = piece.superview else { return }
        let translation = pan.translation(in: superview)

        switch pan.state {
        case .began, .changed:
            piece.center = CGPoint(x: piece.center.x + translation.x,
                                   y: piece.center.y + translation.y)
            pan.setTranslation(.zero, in: superview)
            self.isPinching = true

        case .ended, .cancelled:
            self.isPinching = false
            // 平移结束后检查边界
            checkAndAdjustBounds(for: piece, animated: true)
            print("平移")

        default:
            break
        }
    }

    // 边界检查方法（只在手势结束时调用）
    private func checkAndAdjustBounds(for view: UIView, animated: Bool = false) {
        guard let superview = view.superview else { return }
        
        let transformedFrame = view.convert(view.bounds, to: superview)
        let superBounds = superview.bounds
        
        var finalFrame = transformedFrame
        var needsAdjustment = false
        
        // 检查左边界 - 如果左边界在父视图内部，就拉到左对齐
        if transformedFrame.minX > superBounds.minX {
            finalFrame.origin.x = superBounds.minX
            needsAdjustment = true
        }
        
        // 检查右边界 - 如果右边界在父视图内部，就拉到右对齐
        if transformedFrame.maxX < superBounds.maxX {
            finalFrame.origin.x = superBounds.maxX - transformedFrame.width
            needsAdjustment = true
        }
        
        // 检查上边界 - 如果上边界在父视图内部，就拉到上对齐
        if transformedFrame.minY > superBounds.minY {
            finalFrame.origin.y = superBounds.minY
            needsAdjustment = true
        }
        
        // 检查下边界 - 如果下边界在父视图内部，就拉到下对齐
        if transformedFrame.maxY < superBounds.maxY {
            finalFrame.origin.y = superBounds.maxY - transformedFrame.height
            needsAdjustment = true
        }
        
        // 如果需要调整边界
        if needsAdjustment {
            let newCenter = CGPoint(
                x: finalFrame.midX,
                y: finalFrame.midY
            )
            
            if animated {
                UIView.animate(withDuration: 0.35,
                               delay: 0,
                               usingSpringWithDamping: 0.8,
                               initialSpringVelocity: 1.0,
                               options: [.curveEaseOut]) {
                    view.center = newCenter
                }
            } else {
                view.center = newCenter
            }
        }
    }

    // 允许同时识别缩放和平移手势
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return (gestureRecognizer is UIPinchGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer) ||
               (gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPinchGestureRecognizer)
    }
}


